﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PrintingServer.ServerBase;
using PrintingServer;
using LogLib;
using IPrinting;

namespace PrintingServer.ClientCommands
{
    public class Exit : ClientRequestPackCommand<PrintDataPackge>
    {
        public IPhotoPrint PrintApp = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public PhotoPrintingServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, PrintDataPackge pack)
        {
            Session = session;
            Server = session.AppServer as PhotoPrintingServer;
            Server.OnNewSessionRequestReceived(session, pack);
            if (!Server.PrintApps.ContainsKey(pack.Invoker))
            {
                Log.WriteAsync("不存在的接口:" + pack.Invoker);
                return;
            }
            PrintApp = Server.PrintApps[pack.Invoker];
            if (PrintApp == null)
            {
                Log.WriteAsync("接口对象为空:" + pack.Invoker);
                return;
            }
            string outstring = "";
            try
            {
                PrintApp.Exit();
                if (PrintApp.Exited)
                {
                    OnExitOK(outstring);
                }
                else
                {
                    OnExitFailed(PrintApp.ErrorMessage, outstring);
                }
            }
            catch (Exception ex)
            {
                Server.OnCatchException(session, PrintApp, PrintAction.Exit, ex);
            }     
        }


        protected void OnExitOK(string outParams = "")
        {
            PrintResponsePackge pack = new PrintResponsePackge(PrintApp.Name, PrintAction.Exit);
            pack.Success = true;
            pack.Result = PrintResult.ExitOK;
            pack.Message = "";
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }    
            Server.ReportPrintingReponse(pack);
        }

        protected void OnExitFailed(string reasonMsg, string outParams)
        {
            PrintResponsePackge pack = new PrintResponsePackge(PrintApp.Name, PrintAction.Exit);
            pack.Success = false;
            pack.Result = PrintResult.ExitFailed;
            pack.Message = reasonMsg;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }    
            Server.ReportPrintingReponse(pack);
        }
    }
}
